<?php
/**
 * Created by PhpStorm.
 * User: zhangtao
 * Date: 16-5-24
 * Time: 下午7:35
 */

namespace Home\Controller;


use Think\Controller;

class OrderController extends Controller
{
    public function add()
    {
        $order = M('Order');
        $data['setorder_time'] = date('Y-m-d H:m:s');
        $data['id'] = date('ymdHis') . substr(microtime(), 2, 4);
        $data['state'] = 1;
        $data['address_id'] = I('post.address_id');
        $data['dish_id_string'] = I('post.dish_id_string');
        $data['store_id'] = I('post.store_id');
        $data['remark'] = I('post.remark');
        $data['payment_type'] = I('post.payment_type');
        $data['time_from_setorder'] = time();
        $data['username'] = I('post.username');
        $data['discount_result'] = I('post.discount_result');
        $data['total_price'] = I('post.total_price');
        if ($order->create($data)) {
            $result = $order->add();
            if ($result)
                $this->ajaxReturn(array('status' => 'success', 'id' => $data['id']));
            else
                $this->ajaxReturn(array('status' => 'fail'));
        } else {
            $this->ajaxReturn(array('status' => 'fail'));
        }
    }

    public function update()
    {
        $order = M('Order');
        if ($order->field('state')->create()) {
            $order->startTrans();
            if ($order->where(array('id' => I('post.id')))->save()) {
                $map = $order->field('time_from_setorder')->where(array('id' => I('post.id')))->find();
                $map['time_from_setorder'] = $map['time_from_setorder'] . '-' . time();
                if ($order->where(array('id' => I('post.id')))->save($map)) {
                    $order->commit();
                    $this->ajaxReturn(array('status' => 'success'));
                } else {
                    $order->rollback();
                    $this->ajaxReturn(array('status' => 'fail'));
                }
            } else
                $this->ajaxReturn(array('status' => 'fail'));
        } else {
            $this->ajaxReturn(array('status' => 'fail'));
        }

    }

    public function orderlist()
    {
        $order = M('Order');
        if (I('post.state') != 0) {
            $orderList = $order->field('send_time,comment_id', true)->where(I('post.'))->order('setorder_time desc')->select();
        } else {
            $orderList = $order->field('send_time,comment_id', true)->where(array('username'=>I('post.username')))->order('setorder_time desc')->select();
        }
        $this->ajaxReturn($orderList);
    }
}